var express = require("express");
var path = require("path");

var app = express();
var artTemplate = require("express-art-template");

app.engine("html", artTemplate);

app.set("views", path.join(__dirname, "views"));
var mongoose = require("mongoose");

mongoose.connect(
  "mongodb://127.0.0.1:27017/Relation",
  {
    useNewUrlParser: true,
    useUnifiedTopology: true
  },
  function(err) {
    if (err) {
      console.log(err);
      console.log("数据库连接失败");
    } else {
      console.log("数据库连接成功");
    }
  }
);

var Message = mongoose.model("mes", {
  time1: String,
  time2: String,
  host: String,
  txt: String,
  reply: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'rep'
}]
});

var Reply=mongoose.model("rep", {
  time1: String,
  time2: String,
  host: String,
  txt: String
});

app.get("/mess", function(req, res) {
  var txt = req.query.txt;
  var now = new Date();
  var time1 =
    now.getFullYear() + "年" + now.getMonth() + 1 + "月" + now.getDate() + "日";
  var time2 = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
  var host = "127.0.0.1";
 
  var data = { time1, time2, host, txt };
  
  var stu = new Message(data);
  // 向数据库插入一条数据
  stu.save(function(err) {
    if (err) {
      console.log(err);
      console.log("保存失败");
    } else {
      console.log("保存成功");
    }
  });
  res.redirect("/");
});

app.get("/Replay/:aid", function(req, res) {
  var txt = req.query.txt;
  var now = new Date();
  var time1 =
    now.getFullYear() + "年" + now.getMonth() + 1 + "月" + now.getDate() + "日";
  var time2 = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
  var host = req.ip;
  var reply=req.params.aid
  
  var data = { time1, time2, host, txt };
  
  var ply = new Reply(data);
  // 向数据库插入一条数据
  ply.save(function(err,rea) {
    if (err) {
      console.log(err);
      console.log("保存失败");
    } else {
      console.log(rea);
      var aa=rea._id
      Message.updateOne(
        {
          _id: reply
        },
        {
          $push: {
            reply:  mongoose.mongo.ObjectId(aa)
          }
        },
        function(err) {
          if (err) {
              console.log(err);
            console.log("更新失败");
          } else {
            console.log("更新成功");
          }
        }
      );
      console.log("保存成功");
    }
  });
  res.redirect("/");
});

app.get("/", function(req, res) {
  Message.find().populate('reply').exec(function (err,content) {
    res.render("index.html", { content});
  });
});

app.listen(5555, function() {
  console.log("服务器启动...");
});
